define(function(require, exports, module) {

	var $ = require('jquery');
	var List = require('../util/list');
	require('artTemplate/artTemplate/2.0.1/template.js');
	require('seajs/seajs/2.1.1/sea.js');
	require('jquery/jquery-form/1.0.0/jquery.form.js');
	require('jquery/jquery-validation/1.11.0/jquery.validate');
	require('jquery/jquery-validation/1.11.0/messages_zh');
	require('jscal2/jscal2/1.9/jscal2.js');
	require('jscal2/jscal2/1.9/lang/cn.js');
	require('jbox');
	
	exports.options = {
		listLink : '',
		listParams : '',
		pageLink : '',
		pageParams : ''
	};
	
	var uid=g_user.id;	
	var sum = 0;
	var sum_pro = 0;

	// 获得当前日期
	var today = new Date();
	var y = today.getFullYear(); // 获取完整的年份(4位,1970-????)
	var m = today.getMonth() + 1; // 获取当前月份(0-11,0代表1月)
	var d = today.getDate(); // 获取当前日(1-31)
	var t_today = ''; // 获取当前时间
	if (m < 10) {
		m = 0 + "" + m;
		t_today = parseInt(y + "" + m + "" + d);
	} else {
		t_today = parseInt(y + "" + m + "" + d);
	}
	
	
	
	// 服务分类加载
	exports.options.listLink = $CONFIG.base_url + "/api/category";
	var categoryList = $.get(exports.options.listLink);
	categoryList.done(function(data) {
		sum = data.projectCategories.length;
		var selectKind = template.render('peojectFl-template', data);
		$('#join-project').append(selectKind);
		// 选择分类筛选
	});

	//全选/全不选
	$("input[name=projectCategory0]").click(function(){
		if($(this).attr("checked")){
			for(var i=1;i<=sum;i++){
				$("input[name=projectCategory"+i+"]").attr("checked",true);
			}
		}
		else {
			for(var i=1;i<=sum;i++){
				$("input[name=projectCategory"+i+"]").attr("checked",false);
			}
		}
	})
	
	//添加服务列表
	exports.showProjectList = function showProjectList() {
		var getting = $.get($CONFIG.base_url + "/api/project/income/projectName/list");
		getting.done(function(data) {
			$.each(data,function(key,val){
				sum_pro=data.length;
				var $input = $("<input type='checkbox' name='project"+val[0] + 
					"' value=" + val[0] + " style='margin:0;'><span>"+ val[1]+"<span><br>");
				$("#coupon-project").append($input);
			});
		});
	};

	exports.showProjectList();

	//添加服务
	$("#add-submit").click(function(){
		$("#coupon-project input").each(function(){
			if($(this).attr("checked")){
				var text = $(this).next().text();
				$(this).next().remove();
				$(this).insertBefore($("#add-project"));
				$(this).after("<span style='padding-right:10px;'>"+text+"</span>");
			}
		});
		$("#upModal .close").click();
	});
	
	// 添加日历
	exports.showCalander = function showCalander(e, min,fn) {
		Calendar.setup({
			weekNumbers : true,
			selectionType : Calendar.SEL_SINGLE,
			inputField : e,
			trigger : e,
			onSelect : function() {				
				this.hide();
				if(typeof(fn)=="function"){
					fn();
				}
			},
			showTime : true,
			dateFormat : "%Y-%m-%d %I:%M:%S",
			min : min,
			minuteStep:1
		});
	};
	$("#startTime1").focus(function(){
		exports.showCalander("startTime1","1970011",function(){
			exports.showCalander("endTime1",$("#startTime1").val(),function(){
				
			});
		});
	});
	$("#startTime2").focus(function(){
		exports.showCalander("startTime2","1970011",function(){
			exports.showCalander("endTime2",$("#startTime2").val(),function(){
				
			});
		});
	});
	$("#overduateDate").focus(function(){
		exports.showCalander("overduateDate",t_today,function(){
			coupon_overduateDate = $("input[id=overduateDate]").val();
		});//获取优惠券过期时间
	});

	
	
	//筛选用户
	$("#chooseUser").click(function(e){
		e.preventDefault();
		var vald1 = '';
		var vald2 = '';
		$(".required").each(function(){
			if($(this).val() == ""){
				vald1=$(this).attr("name");
			}
		})
		switch(vald1){
		case "registDateStart":
			$.jBox.tip("亲~注册时间起始时间不能为空哦！");
			$(this).focus();
			return;
			break;
		case "registDateEnd":
			$.jBox.tip("亲~注册时间结束时间不能为空哦！");
			$(this).focus();
			return;
			break;
		case "comsumptionDateStart":
			$.jBox.tip("亲~消费时间起始时间不能为空哦！");
			$(this).focus();
			return;
			break;
		case "comsumptionDateEnd":
			$.jBox.tip("亲~消费时间结束时间不能为空哦！");
			$(this).focus();
			return;
			break;
		}

		$(".price").each(function(){
			if(isNaN($(this).val())){
				vald2=$(this).attr("name");
			}
				
		})
		switch(vald2){
		case "comsumptionFee":
			$.jBox.tip("亲~单次消费最低金额必须为数字哦！");
			$(this).focus();
			return;
			break;
		case "comsumptionTotleFee":
			$.jBox.tip("亲~总消费最低金额必须为数字哦！");
			$(this).focus();
			return;
			break;
		}

		var postData = form2js("chooseUser-form", '.', true);
		postData.addressId ="0";
		postData["created_by.id"] = uid;

		postData["projectIds"]= '';
		delete postData["projectCategory0"];
		postData["projectCategoryIds"] = '';

		for(var i=1;i<=sum;i++){
			if(postData["projectCategory"+i] != null){
				postData["projectCategoryIds"] += postData["projectCategory"+i];
				delete postData["projectCategory"+i];
				postData["projectCategoryIds"] += ',';
			}
		}

		for(var i=1;i<=sum_pro;i++){
			if(postData["project"+i] != null){
				postData["projectIds"] += postData["project"+i] ;
				delete postData["project"+i] ;
				postData["projectIds"] += ",";
			}
		}
		 var provide=$.post($CONFIG.base_url + "/api/project/income/coupon/selectUsers",postData);
		 provide.done(function(data){
			 for(var i=0;i<data.UserIds.length;i++){
			 	$("#chosenUser").append('<input type="checkbox" class="check" checked="checked" name=user["'+
			 		i+'"] value="'+data.UserIds[i]+'='+data.projectIds[i]+'" style="margin:0;">'
			 		+'<span>'+data.UserName[i]+'&nbsp'+'</span>');
			 }
		 }).fail(function(data){
			 $.jBox.tip("亲~出错啦，再试一次！");
		 });
	})

	$("#chosenUser").on('click','.check',function(){
	 	if($(this).prop("checked")==false){
	 		$(this).next().remove();
	 		$(this).remove();
	 	}
	 })
		
	
	//点击发送按钮
	$("#sent").click(function(e){
		e.preventDefault();
		
		var vald1 = '';
		var vald2 = '';
		$(".required").each(function(){
			if($(this).val() == ""){
				vald1=$(this).attr("name");
				//console.log(vald1);
			}
		})
		switch(vald1){
		case "label":
			$.jBox.tip("亲~优惠券类型不能为空哦！");
			$(this).focus();
			return;
			break;
		case "couponExplain":
			$.jBox.tip("亲~优惠券简介不能为空哦！");
			$(this).focus();
			return;
			break;
		case "couponValue":
			$.jBox.tip("亲~优惠券价值不能为空哦！");
			$(this).focus();
			return;
			break;
		case "overduateDate":
			$.jBox.tip("亲~优惠券过期时间不能为空哦！");
			$(this).focus();
			return;
			break;
		}
		
		$(".price").each(function(){
			if(isNaN($(this).val())){
				vald2=$(this).attr("name");
			}
				
		})
		switch(vald2){
		case "couponValue":
			$.jBox.tip("亲~优惠券价值必须为数字哦！");
			$(this).focus();
			return;
			break;
		}
		
		
		var userNames='';
		$("#chosenUser input").each(function(){
			userNames += $(this).next().text() + ', '
		})
		
		var postData = form2js("coupon-provide-form", '.', true);
		postData.addressId ="0";
		postData["created_by.id"] = uid;
		postData["users"] = '';
		for(var i=0;i<postData.user.length;i++){
			postData["users"]+=postData.user[i];
			postData["users"]+=",";
		}
		delete postData.user ;
		//console.log(postData);
		var submit = function (v, h, f) {
		    if (v == 'ok'){
		    	var provide=$.post($CONFIG.base_url + "/api/project/income/coupon/give",postData);
				 provide.done(function(data){
					 if(data > 0){
						 $.jBox.tip("派发优惠券成功！共派发了"+data+"张优惠券");
							setTimeout(function(){window.location.href=$CONFIG.base_url + '/'+$CONFIG.admin_url+'/manage/coupon';},1000);
					 }else{
						 $.jBox.tip("派发优惠券失败！");
					 }
				 }).fail(function(data){
					 $.jBox.tip("亲~出错啦，再试一次！");
				 });
		    }
		    
		};
		$.jBox.confirm("将要向以下用户派发优惠券："+userNames, "<span style='text-align:center;width:100%;display:block;color: #834313;'>友情提示</span>", submit);
		 
	});
});